﻿// PrinterViewModel.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Media.Imaging;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NewUI.Component; // 添加 MVVM 命令支持
using Printer;

namespace NewUI.ViewModels;

public partial class PrinterViewModel : ViewModelBase
{
    public PrinterViewModel()
    {
        Initialize();
    }

    public class ImageItem : ObservableObject
    {
        public Bitmap? Image { get; set; }
        public string? FileName { get; set; }
        public string? FullPath { get; set; }
        
        private bool _isSelected;
        public bool IsSelected
        {
            get => _isSelected;
            set => SetProperty(ref _isSelected, value);
        }
    }
    
    

    [ObservableProperty]
    private ObservableCollection<ImageItem> _imageItems = new();

    [ObservableProperty]
    private bool _isDeleting;

    private FileSystemWatcher? _imageWatcher;
    private string? _imageDirectory;
    
    public void Initialize()
    {
        InitializeImageGallery();
    }

    [RelayCommand]
    public async Task PrintLabel()
    {
        foreach (var item in ImageItems)
        {
            if (item.IsSelected)
            {
                string label = item.FileName;
                var btwPath = Path.Combine(
                    Path.GetDirectoryName(_imageDirectory) ?? "",
                    Path.ChangeExtension(item.FileName, ".btw")
                );
                if (!File.Exists(btwPath))
                {
                    ToastManager.ShowErrorToast("下发打印异常，系统找不到当前模板文件!");
                }
                else
                {
                    BartenderPrinterUtil.DoPrint(label);
                    Task.Delay(500); 
                    ToastManager.ShowSuccessToast("发送打印指令成功!");
                }
              
            }
        }
       
    }

    [RelayCommand]
    public async Task DeleteSelectedImages()
    {
        if (IsDeleting) return;
        
        try
        {
            IsDeleting = true;
            
            // 获取选中的图片项
            var selectedItems = ImageItems.Where(item => item.IsSelected).ToList();
            if (!selectedItems.Any())
            {
                Debug.WriteLine("没有选中任何图片");
                return;
            }

            // 确认删除
            var result = await ShowConfirmationDialog("确认删除", $"确定要删除选中的 {selectedItems.Count} 张图片和相关模板吗?");
            if (!result) return;

            // 禁用文件监听器，避免删除操作触发重新加载
            if (_imageWatcher != null)
            {
                _imageWatcher.EnableRaisingEvents = false;
            }

            // 删除文件
            foreach (var item in selectedItems)
            {
                try
                {
                    if (item.FullPath != null && File.Exists(item.FullPath))
                    {
                        File.Delete(item.FullPath);
                        Debug.WriteLine($"已删除图片: {item.FullPath}");
                    }

                    // 删除同名 BTW 文件
                    if (item.FileName != null && _imageDirectory != null)
                    {
                        var btwPath = Path.Combine(
                            Path.GetDirectoryName(_imageDirectory) ?? "",
                            Path.ChangeExtension(item.FileName, ".btw")
                        );

                        if (File.Exists(btwPath))
                        {
                            File.Delete(btwPath);
                            Debug.WriteLine($"已删除模板: {btwPath}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"删除文件失败: {item.FileName} - {ex.Message}");
                }
            }

            // 从集合中移除已删除项
            foreach (var item in selectedItems)
            {
                ImageItems.Remove(item);
                item.Image?.Dispose();
            }
        }
        finally
        {
            // 重新启用文件监听器
            if (_imageWatcher != null)
            {
                _imageWatcher.EnableRaisingEvents = true;
            }
            
            IsDeleting = false;
        }
    }

    // 模拟确认对话框（实际应用中应使用对话框服务）
    private async Task<bool> ShowConfirmationDialog(string title, string message)
    {
        Debug.WriteLine($"{title}: {message}");
        // 在实际应用中，这里应该调用对话框服务
        // return await _dialogService.ShowConfirmation(title, message);
        return true; // 模拟用户确认
    }

    private void InitializeImageGallery()
    {
        // 设置图片目录路径
        var exeDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        if (exeDir == null) return;
        
        _imageDirectory = Path.Combine(exeDir, "BtwTemplates", "Images");
        
        // 确保目录存在
        Directory.CreateDirectory(_imageDirectory);
        
        // 初始加载图片
        LoadImages();
        
        // 设置文件系统监听
        SetupFileWatcher();
    }

    private void SetupFileWatcher()
    {
        try
        {
            if (_imageDirectory == null) return;
            
            // 释放旧的监听器
            _imageWatcher?.Dispose();
            
            _imageWatcher = new FileSystemWatcher
            {
                Path = _imageDirectory,
                NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size,
                Filter = "*.*",
                IncludeSubdirectories = false,
            };

            // 增加缓冲区大小
            _imageWatcher.InternalBufferSize = 65536;

            // 添加事件处理
            _imageWatcher.Created += OnImageDirectoryChanged;
            _imageWatcher.Deleted += OnImageDirectoryChanged;
            _imageWatcher.Renamed += OnImageDirectoryChanged;
            _imageWatcher.Changed += OnImageDirectoryChanged;
            
            _imageWatcher.EnableRaisingEvents = true;
            Debug.WriteLine($"文件监听器已启动: {_imageDirectory}");
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"文件监听器启动失败: {ex}");
        }
    }
    
    private void OnImageDirectoryChanged(object sender, FileSystemEventArgs e)
    {
        // 防抖处理：避免快速连续触发
        Dispatcher.UIThread.InvokeAsync(LoadImages);
    }

    private void LoadImages()
    {
        try
        {
            if (_imageDirectory == null) return;
            
            var imageFiles = Directory.GetFiles(_imageDirectory)
                .Where(file => 
                    file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
                    file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
                    file.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) ||
                    file.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) ||
                    file.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))
                .ToList();

            var tempList = new List<ImageItem>();
            foreach (var imagePath in imageFiles)
            {
                try
                {
                    tempList.Add(new ImageItem
                    {
                        Image = new Bitmap(imagePath),
                        FileName = Path.GetFileNameWithoutExtension(imagePath),
                        FullPath = imagePath
                    });
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"加载图片失败: {imagePath} - {ex.Message}");
                }
            }

            // 更新可观察集合
            ImageItems = new ObservableCollection<ImageItem>(tempList);
            OnPropertyChanged(nameof(ImageItems));
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"加载图片列表失败: {ex.Message}");
        }
    }

    // 清理资源
    public void Cleanup()
    {
        _imageWatcher?.Dispose();
        _imageWatcher = null;
        
        // 释放图片资源
        foreach (var item in ImageItems)
        {
            item.Image?.Dispose();
        }
        ImageItems.Clear();
    }
    
    // 其他方法保持不变...
}